// import axios from '../common/axios.min.js'
// import {Message} from '../common/element-ui_lib_index.js'
// import {getStore, removeStore, setStore} from './mUtils'
// import Router from 'vue-router'
// import Router from '@/router/index'

const $http = async function (url, data = {}, method = 'GET', responseType = 'json') {
  let config = {
    url,
    method,
    timeout: 30000,
    withCredentials: true,
    responseType: responseType,
    // headers,
  }
  if (config.method.toUpperCase() === 'POST') {
    config.data = data
  } else {
    config.params = data
  }
  // console.log(axios)
  return axios.request(config)
}

let vue = new Vue({

})

// POST传参序列化(添加请求拦截器)
axios.interceptors.request.use(config => {
  // 在发送请求之前做某件事
  // let token = getStore('token')
  let token = "getStore('token')"
  if (token) {
    token = token.replace(/'|"/g, '') // 把token加入到默认请求参数中
    config.headers.common['Authorization'] = token
  }
  return config
}, error => {
  return Promise.reject(error)
})
let vm = new Vue({

})
// 返回状态判断(添加响应拦截器)
axios.interceptors.response.use(res => {
  let that = this
  //是否是导出数据
  if (res.config.responseType === 'blob') {
    axiosDownload(res)
    return res
  }
  // 需要登陆
  if (res.data === null) {
    // removeStore('token')
    // Message.info('登录失效, 请重新登录')
    // Router.push({path: '/login'})
  }


  if (res.data.code === 401 || res.data.code === 402 || res.data.code === 403) {
    // removeStore('token')
    var storage = window.localStorage;
    storage.clear()
    // Message.info('登录失效, 请重新登录')
    // Router.push({path: '/login'})
  } else {
    // 判断token是否存在，如果存在说明需要更新token
    if (res.data != null && res.data.data != null && res.data.data.token != null) {
      // setStore('token', res.data.data.token) // 覆盖原来的token(默认一天刷新一次)
    }

  }
  //服务器返回异常统一在此处理
  if (res.data.code !== 20000){
    // alert(res.data.message)
    vm.$message.error(res.data.message)
  }

  return res.data
}, error => {
  return Promise.reject(error)
})

const axiosDownload = function (res) {
  if (!res.data) {
    Message.error('下载失败，服务器或网络异常')
    return
  }
  const content = res.data
  const blob = new Blob([content])
  let fileName = '下载文件.xlsx'
  const contentDisposition = res.headers['content-disposition']
  if (contentDisposition) {
    fileName = window.decodeURI(res.headers['content-disposition'].split('=')[1])
  }
  if ('download' in document.createElement('a')) { // 非IE下载
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href) // 释放URL 对象
    document.body.removeChild(elink)
  } else { // IE10+下载
    navigator.msSaveBlob(blob, fileName)
  }
}

$http.install = (Vue) => {
  Vue.prototype.$http = $http
}

export default $http
